/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ppsa.Servlet;

import com.ppsa.bean.DocumentoBean;
import com.ppsa.bean.UsuarioBean;
import com.ppsa.logic.MantenimientoLogic;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.ObjectUtils;
/**
 *
 * @author AdminTdp
 */
@WebServlet(name = "ServletArchivo", urlPatterns = {"/ServletArchivo"})
public class ServletArchivo extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        //Document document = new Document();
        //PdfWriter writer = null;
        String strpv_codigoDocumento = ObjectUtils.toString(request.getParameter("strpv_codigoDocumento"));

        MantenimientoLogic objL_logic = new MantenimientoLogic();
        String documentoUrlPDF = null;
        DocumentoBean objL_documento = new DocumentoBean();
        //if ((strL_codigoPdf).equals("001")) {
        HttpSession objL_sesion = objL_sesion = request.getSession(true);
        UsuarioBean objL_usuarioBeanSession = new UsuarioBean();
        objL_usuarioBeanSession = (UsuarioBean) objL_sesion.getAttribute("objL_usuario");
        System.out.println("CODIGO DEL DOCUMENTO -->" + strpv_codigoDocumento);

        try {
            objL_documento = objL_logic.obtenerUrlPDF(strpv_codigoDocumento, objL_usuarioBeanSession);
            MantenimientoLogic objmany = new MantenimientoLogic();
            //objmany.generarPDF();
        } catch ( Exception ex ) {

            ex.printStackTrace();
        }
      
        
            response.setHeader("Expires", "0");
            //response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            //response.setHeader("Pragma", "public");
            response.setHeader("Content-Type","application/octet-stream");
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition", "attachment; filename="+objL_documento.getStrpv_codigoReferencial()+".pdf");

            
            //ServletOutputStream out = response.getOutputStream();
            //baos2.writeTo(out);
           FileInputStream baos = new FileInputStream("d:\\pdf\\"+objL_documento.getStrpv_urlPDFDocumento()+".pdf");
            OutputStream os = response.getOutputStream();
            
            

            byte buffer[] = new byte[8192];
            int bytesRead;

            while ((bytesRead = baos.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }

            os.flush();
            os.close();
       // }      
                  
            
        /*
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ServletArchivo</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet ServletArchivo at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }*/
    }
    /* private static void poneSelloAgua(PdfWriter writer) {
           try {
               PdfContentByte cb = writer.getDirectContent();
               //Se crea un templete para asignar la marca de agua
               PdfTemplate template = cb.createTemplate(700, 300);
               template.beginText();
               //Inicializamos los valores para el templete
               //Se define el tipo de letra, color y tamaño
               BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
               //template.setColorFill(new Color(220, 220, 220));
               template.setFontAndSize(bf, 6);
               
               template.setTextMatrix(0, 0);
               //Se define el texto que se agregara como marca de agua
               template.showText("TEXTO MARCA AGUA");
               template.endText();
               //Se asigna el templete
               //Se asignan los valores para el texto de marca de agua
               // Se asigna el grado de inclinacion y la posicion donde aparecerá el texto
               //                                                     x    y
               cb.addTemplate(template, 1, 1, -1,1, 50, 500);
           }
           catch (Exception e) {
               e.printStackTrace();
           }
       }*/
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
